<?php
namespace Home\ Controller;
use\ Home\ Model\ LoginModel;
use\ Home\ Controller\ SafeController;
use\ Home\ Controller\ MailController;
final class LoginController {
	//加载注册视图
	public function regView() {
		include VIEW_PATH . "login.html";
	}
	//加载登陆视图
	public function loginView() {
		//判断来源。
		//$_SERVER['HTTP_REFERER']是判断访问这个页面上个页面的地址。
		//$_SERVER['HTTP_HOST']是主机名
		//暂时注释掉IF语句，凡是进入登陆界面都注销SESSION
		//if($_SERVER['HTTP_REFERER']=='http://'.$_SERVER['HTTP_HOST'].'/index.php?c=User&a=home'){//如果来自于个人空间
		//开始session
		session_start();
		//删除
		session_unset();
		//注销
		session_destroy();
		//echo "<script>location.herf='./';</script>";
		//Cookie设置为过去
		$expire=time()-60;//五天
		setcookie("uid", "", $expire);
		setcookie("name", "", $expire);
		setcookie("qq", "", $expire);
		setcookie("sex", "", $expire);
		//}
		//加载登录页面
		include VIEW_PATH . "login.html";
	}
	//加载找回密码视图
	public function retrievePasswordView() {
		include VIEW_PATH . "retrieve.html";
	}
	//注册方法
	public function reg() {
	    session_start();
		$server = $_POST[ 'server' ];
		$token = $_POST[ 'token' ];
		$safeObj = new SafeController();
		$res = $safeObj->vaptcha( $server, $token, 2 ); //这里返回回来之前已经把json转为数组
		//首先对手势验证进行评判，低于设定分数则返回一个重新错误及重新验证
		if ( $res[ 'score' ] < $GLOBALS[ 'config' ][ 'score' ] ) {
			$code = 500;
			$msg = '安全验证得分过低，请重新验证后提交';
			//返回数组的构建
			$result = [
				"code" => $code,
				"msg" => $msg,
				"err" => $res[ 'msg' ]
			];
			$json = json_encode( $result );
			echo $json;
			return;
		}

		$acc = $_POST[ 'account' ];
		$pwd = $_POST[ 'password' ];
		//$name = $_POST[ 'name' ];
		$name = "博书公益用户".date("ymdH").mt_rand(100,999);
		$email = $_POST[ 'email' ];
		$phone = $_POST[ 'phone' ];
		//$sex = $_POST[ 'sex' ];
		$sex = 0;
		$qq = $_POST[ 'qq' ];

		//对其他输入内容进行过滤SimpleClean
		$safeObj = new SafeController();
		$loginModelObj = new LoginModel();

		$acc = $safeObj->simpleClean( $acc );
		$name = $safeObj->simpleClean( $name );
		$email = $safeObj->simpleClean( $email );
		$phone = $safeObj->simpleClean( $phone );
		//$sex = $safeObj->simpleClean($sex);
		$qq = $safeObj->simpleClean( $qq );
		//对密码进行严格过滤 cleanAll，后面登录执行同样的过滤，这样尽管会有些字符被过滤掉，但被过滤后的字符串是一样的，不会影响判断
		$pwd = $safeObj->cleanAll( $pwd );
		//散列
		$pwd = md5( $pwd );

		//判断用户名
		$flagAcc = $this->_isAccountExist( $acc );
		//判断手机号
		$flagPhone = $this->_isPhoneExist( $phone );
		//判断邮箱
		$flagEmail = $this->_isEmailExist( $email );

		//定义返回的变量，为空
		$code = null;
		$msg = null;

		//对各flag进行判断，只有三个都为1才能进行插入，否则都返回错误信息到前端
		if ( $flagAcc == 1 && $flagEmail == 1 && $flagPhone == 1 ) {
			//满足
			$row = $loginModelObj->register( $acc, $pwd, $name, $email, $phone, $sex, $qq );
			if ( $row == 1 ) {
				$code = 200;
				$msg = '注册成功';
			} else {
				$code = 500;
				$msg = '注册失败';
			}
		} else if ( $flagAcc == 0 ) {
			//账户存在
			$code = 500;
			$msg = '账户名已存在';
		} else if ( $flagEmail == 0 ) {
			//邮箱存在
			$code = 500;
			$msg = '邮箱已存在';
		} else if ( $flagPhone == 0 ) {
			//手机存在
			$code = 500;
			$msg = '手机号已存在';
		}

		//返回数组的构建
		$result = [
			"code" => $code,
			"msg" => $msg
		];
		$json = json_encode( $result );
		echo $json;
	}
	//登录方法
	public function login() {
		session_start();
		//进行手势验证的安全得分评估
		$server = $_POST[ 'server' ];
		$token = $_POST[ 'token' ];
		$safeObj = new SafeController();
		$res = $safeObj->vaptcha( $server, $token, 1 ); //这里返回回来之前已经把json转为数组
		//首先对手势验证进行评判，低于设定分数则返回一个重新错误及重新验证
		if ( $res[ 'score' ] < $GLOBALS[ 'config' ][ 'score' ] ) {
			$result = [
			    "code" => 500,
			    "msg" => "安全验证不通过！"
		    ];
		    $json = json_encode( $result );
		    echo $json;
			return;
		}

		$acc = $_POST[ 'account' ];
		$pwd = $_POST[ 'password' ];

		$safeObj = new SafeController();
		//过滤账号密码
		$acc = $safeObj->simpleClean( $acc );
		$pwd = $safeObj->cleanAll( $pwd );
		//密码md5
		$md5pwd = md5( $pwd );

		$loginModelObj = new LoginModel();

		//开始进行账号密码正确性判断
		$login = $loginModelObj->login( $acc, $md5pwd );
		if ( !$login ) {
			$result = [
			    "code" => 500,
			    "msg" => "用户名或密码错误！"
		    ];
		    $json = json_encode( $result );
		    echo $json;
			return;
		} else {
			//从数据库中查询该条记录
			$query = $loginModelObj->query( $acc );
			//这里写几句COOKIE的，后端先用SESSION
						$expire=time()+60*60*24;//五天
						setcookie("uid", $query['uid'], $expire);
						setcookie("name", $query['name'], $expire);
						setcookie("qq", $query['qq'], $expire);
						setcookie("sex", $query['sex'], $expire);
			$_SESSION[ 'uid' ] = $query[ 'uid' ];
			$_SESSION[ 'account' ] = $query[ 'account' ];
			$_SESSION[ 'password' ] = $query[ 'password' ];
			$_SESSION[ 'name' ] = $query[ 'name' ];
			$_SESSION[ 'qq' ] = $query[ 'qq' ];
			$_SESSION[ 'phone' ] = $query[ 'phone' ];
			$_SESSION[ 'sex' ] = $query[ 'sex' ];
			$_SESSION[ 'email' ] = $query[ 'email' ];
			$result = [
			    "code" => 200,
			    "msg" => "登陆成功！"
		    ];
		    $json = json_encode( $result );
		    echo $json;
			return;
		}
	}

	//找回密码 
	//第一步 验证邮箱和用户名的匹配，匹配则发送验证码
	//第二步 填写验证码和新密码，后端直接全部接受并判断
	//不分成几个页面主要是防止用户绕过第一步
	public function retrievePassword() {
		//进行手势验证的安全得分评估
		$server = $_POST[ 'server' ];
		$token = $_POST[ 'token' ];
		$safeObj = new SafeController();
		$res = $safeObj->vaptcha( $server, $token, 5 ); //这里返回回来之前已经把json转为数组
		//首先对手势验证进行评判，低于设定分数则返回一个重新错误及重新验证,通过就进行后面的处理
		if ( $res[ 'score' ] >= $GLOBALS[ 'config' ][ 'score' ] ) {
			//如果得分通过
			$account = $_POST[ 'account' ];
			$email = $_POST[ 'email' ];
			$code = $_POST[ 'code' ];
			$pwd1 = $_POST[ 'newpwd1' ];
			$pwd2 = $_POST[ 'newpwd2' ];
			$account = $safeObj->simpleClean( $account );
			$email = $safeObj->simpleClean( $email );
			$code = $safeObj->simpleClean( $code );
			//密码后面会进行处理的
			//判断账号和邮箱是否匹配
			$res1 = $this->_isAccEmailMatch( $account, $email ); //$res1是匹配与否的结果
			if ( $res1 == 1 ) {
				//获取验证码并匹配，注意判断时间是否为10分钟内
				$arr = $safeObj->getCode( $account ); //这里是fetchOne结果集数组
				//先判断有没有值，为空要返回错误
				if ( $arr[ 'code' ] != null ) {
					//把datetime转为时间戳
					$time = strtotime( $arr[ 'code_time' ] );
					$now = time();
					$pasttime = $now - $time;
					if ( $pasttime < 600 ) {
						if ( $code == $arr[ 'code' ] ) {
							//判断两次密码是否相等
							if ( $pwd1 == $pwd2 ) {
								//对密码进行过滤和散列
								$pwd = $safeObj->cleanAll( $pwd1 );
								$pwd = md5( $pwd );

								//对密码在数据库中进行更新
								$loginModelObj = new LoginModel();
								$res2 = $loginModelObj->updatePwd( $account, $pwd ); //$resw是修改影响行数
								if ( $res2 == 1 ) {
									$safeObj->delCode( $account );
									$code = 200;
									$msg = '修改成功';
								} else {
									$code = 500;
									$msg = '修改失败，可能是因为新老密码一致所致，也可能是因为服务器原因';
								}
							} else {
								$code = 500;
								$msg = '两次密码不一致';
							}
						} else {
							$code = 500;
							$msg = '验证码错误，请查证后重试';
						}
					} else {
						$code = 500;
						$msg = '验证码已过期，请重新获取';
					}
				} else {
					$code = 500;
					$msg = '服务器错误，请刷新重试';
				}
			} else {
				$code = 500;
				$msg = '账号邮箱不匹配';
			}
		} else {
			$code = 500;
			$msg = '安全验证得分过低，请重新验证并提交';
		}
		$result = [
			"code" => $code,
			"msg" => $msg
		];
		$json = json_encode( $result );
		echo $json;
	}

	//找回密码的邮件发送方法
	public function mailCode() {
		//验证用户名和邮箱是否匹配
		$acc = $_POST[ 'account' ];
		$email = $_POST[ 'email' ];
		$safeObj = new SafeController();
		$account = $safeObj->simpleClean( $account );
		$email = $safeObj->simpleClean( $email );
		$res1 = $this->_isAccEmailMatch( $acc, $email ); //$res1是匹配与否的结果
		if ( $res1 == 1 ) { //说明匹配
			//生成验证码
			$code = $safeObj->code(); //验证码
			$text = "尊敬的用户：<br>&nbsp;&nbsp;&nbsp;&nbsp;您好,您的验证码为 " . $code . " ,您在进行邮箱验证，请妥善保管您的验证码，切记不要让别人知道！如这不是您的操作，请忽视本邮件并且及时修改您的密码<br><br>博书公益团队<br>"; //邮件发送的内容
			//插入到数据库
			$res2 = $safeObj->insertCode( $acc, $code ); //$res2是是否将验证码插入到数据库成功
			if ( $res2 == 1 ) {
				//插入成功
				$mailObj = new MailController(); //生成邮件控制器的对象
				$res3 = $mailObj->sendMail( $email, '博书公益验证码', $text ); //$res3是邮件是否发送成功
				//注意,res3返回的是布尔值true false
				if ( $res3 ) {
					$code = 200;
					$msg = '邮件发送成功';
				} else {
					$code = 500;
					$msg = '邮件发送失败，请重试，若多次重试无效，请联系我们';
				}
			} else {
				$code = 500;
				$msg = '服务器出错，请重试，若多次重试无效，请联系我们';
			}

		} else { //不匹配
			$code = 500;
			$msg = '账号邮箱不匹配';
		}

		$result = [
			"code" => $code,
			"msg" => $msg
		];
		$json = json_encode( $result );
		echo $json;
	}

	//无参的判断,意味着是对外的接口，需要返回编码,echo
	//判断用户名是否存在
	public function isAccountExist() {
		$acc = $_POST[ 'account' ];
		$loginModelObj = new LoginModel();
		$res = $loginModelObj->isAccountExist( $acc );
		if ( $res == 0 ) {
			echo 200;
		} else {
			echo 500;
		}
	}
	//判断手机号是否存在
	public function isPhoneExist() {
		$phone = $_POST[ 'phone' ];
		$loginModelObj = new LoginModel();
		$res = $loginModelObj->isPhoneExist( $phone );
		if ( $res == 0 ) {
			echo 200;
		} else {
			echo 500;
		}
	}
	//判断邮箱是否存在
	public function isEmailExist() {
		$email = $_POST[ 'email' ];
		$loginModelObj = new LoginModel();
		$res = $loginModelObj->isEmailExist( $email );
		if ( $res == 0 ) {
			echo 200;
		} else {
			echo 500;
		}
	}

	//带参的判断，意味着是后端方法，return bool，01
	//判断用户名是否存在
	public function _isAccountExist( $acc ) {
		$loginModelObj = new LoginModel();
		$res = $loginModelObj->isAccountExist( $acc );
		if ( $res == 0 ) {
			return 1;
		} else {
			return 0;
		}
	}
	//判断手机号是否存在
	public function _isPhoneExist( $phone ) {
		$loginModelObj = new LoginModel();
		$res = $loginModelObj->isPhoneExist( $phone );
		if ( $res == 0 ) {
			return 1;
		} else {
			return 0;
		}
	}
	//判断邮箱是否存在
	public function _isEmailExist( $email ) {
		$loginModelObj = new LoginModel();
		$res = $loginModelObj->isEmailExist( $email );
		if ( $res == 0 ) {
			return 1;
		} else {
			return 0;
		}
	}

	//判断用户名和邮箱是否匹配
	public function _isAccEmailMatch( $acc, $email ) {
		$loginModelObj = new LoginModel();
		$res = $loginModelObj->isAccEmailMatch( $acc, $email );
		if ( $res == 1 ) { //结果为1说明正确
			return 1;
		} else {
			return 0;
		}
	}

	//判断密码合法
	public function isPwdLegal() {

	}

	//登录场景的验证vaptcha，这里留着用于测试
	public function vaptcha() {
		$server = $_POST[ 'server' ];
		$token = $_POST[ 'token' ];
		$safeObj = new SafeController();
		$res = $safeObj->vaptcha( $server, $token, 1 );
		if ( $res[ 'success' ] == 1 ) {
			$a = [ 'code' => 200 ];
			$a = json_encode( $a );
			print_r( $a );
		} else {
			$a = [ 'code' => 500 ];
			$a = json_encode( $a );
			print_r( $a );
		}
	}
}
?>